package com.hujun.common.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExecutorUtils {

	private volatile static ThreadPoolExecutor executor;
	private static int corePoolSize = 20;
	private static int maxPoolSize = 100;
	private static long keepAliveTime = 60;
	private static int  queueCapacity = 10;
	
	private ThreadPoolExecutorUtils(){}
	
	public static ThreadPoolExecutor createNewThreadPool(){
		if(executor == null){
			synchronized (ThreadPoolExecutorUtils.class) {
				if(executor == null){
					executor = new ThreadPoolExecutor(corePoolSize, 
							getMaxPoolSize(), 
							getKeepAliveTime(), 
							TimeUnit.SECONDS, 
							new ArrayBlockingQueue<Runnable>(getQueueCapacity()),
							new ThreadPoolExecutor.DiscardPolicy());
				}
				
			}
		}
		return executor;
	}
	
	public static ThreadPoolExecutor createNewThreadPool(int corePoolSize,int maxPoolSize,long keepAliveTime){
		ThreadPoolExecutorUtils.corePoolSize = corePoolSize;
		ThreadPoolExecutorUtils.maxPoolSize = maxPoolSize;
		ThreadPoolExecutorUtils.keepAliveTime = keepAliveTime;
		return createNewThreadPool();
	}
	
	public static void execute(Runnable thread){
		executor.execute(thread);
	}

	public static int getCorePoolSize() {
		return corePoolSize;
	}

	public static void setCorePoolSize(int corePoolSize) {
		ThreadPoolExecutorUtils.corePoolSize = corePoolSize;
	}

	public static int getMaxPoolSize() {
		return maxPoolSize;
	}

	public static void setMaxPoolSize(int maxPoolSize) {
		ThreadPoolExecutorUtils.maxPoolSize = maxPoolSize;
	}

	public static long getKeepAliveTime() {
		return keepAliveTime;
	}


	public static void setKeepAliveTime(long keepAliveTime) {
		ThreadPoolExecutorUtils.keepAliveTime = keepAliveTime;
	}


	public static int getQueueCapacity() {
		return queueCapacity;
	}

	public static void setQueueCapacity(int queueCapacity) {
		ThreadPoolExecutorUtils.queueCapacity = queueCapacity;
	}

	
}
